package edu.sandau.app.basic.controller;

import edu.sandau.app.basic.domain.Order;
import edu.sandau.app.basic.domain.Cart;
import edu.sandau.app.basic.domain.DishWithBLOBs;
import edu.sandau.app.basic.golbal.GlobalEnum;
import edu.sandau.app.basic.service.OrderService;
import edu.sandau.app.basic.service.SysUserService;
import edu.sandau.app.basic.service.CartService;
import edu.sandau.app.basic.service.DishService;
import edu.sandau.app.basic.vo.BasicMsg;
import edu.sandau.app.basic.vo.BasicMsgWithData;
import edu.sandau.app.basic.vo.CreateOrderRequest;
import edu.sandau.app.basic.vo.UpdateOrderRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/orders")
@Tag(name = "订单管理", description = "订单管理接口")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private SysUserService sysUserService;
    
    @Autowired
    private CartService cartService;
    
    @Autowired
    private DishService dishService;
    
    // 获取所有订单
    @GetMapping
    @Operation(summary = "获取所有订单")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功",
            content = @Content(mediaType = "application/json", 
                examples = {
                    @ExampleObject(name = "查询成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": [
                            {
                              "orderNo": "ORD1736316000000",
                              "userId": 1,
                              "totalAmount": 56.00,
                              "orderStatus": "1",
                              "paymentMethod": "微信支付",
                              "paymentTime": "2025-10-08T14:05:00",
                              "deliveryAddress": "北京市朝阳区xxx街道",
                              "contactPhone": "13800138000",
                              "contactName": "张三",
                              "remark": "请尽快送达"
                            },
                            {
                              "orderNo": "ORD1736316000001",
                              "userId": 2,
                              "totalAmount": 28.00,
                              "orderStatus": "0",
                              "paymentMethod": "",
                              "paymentTime": null,
                              "deliveryAddress": "上海市浦东新区xxx路",
                              "contactPhone": "13900139000",
                              "contactName": "李四",
                              "remark": ""
                            }
                          ]
                        }"""),
                    @ExampleObject(name = "暂无订单", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": []
                        }"""),
                    @ExampleObject(name = "查询失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "查询失败: 数据库连接异常",
                          "errorCode": "ORDER_QUERY_FAIL",
                          "data": null
                        }""")
                }))
    })
    public BasicMsgWithData<List<Order>> getAllOrders() {
        BasicMsgWithData<List<Order>> msg = new BasicMsgWithData<>();
        try {
            List<Order> orders = orderService.getAllOrders();
            msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
            msg.setErrorMsg("查询成功");
            msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            msg.setData(orders);
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_QUERY_FAIL);
            msg.setErrorMsg("查询失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 根据ID获取订单
    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取订单")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功",
            content = @Content(mediaType = "application/json", 
                examples = {
                    @ExampleObject(name = "查询成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": {
                            "orderId": 1,
                            "orderNo": "ORD202310090001",
                            "userId": 1,
                            "totalAmount": 68.00,
                            "orderStatus": "1",
                            "paymentMethod": "微信支付",
                            "deliveryAddress": "北京市朝阳区",
                            "contactPhone": "13800138000",
                            "contactName": "张三"
                          }
                        }"""),
                    @ExampleObject(name = "订单不存在", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单不存在",
                          "errorCode": "ORDER_NOT_FOUND",
                          "data": null
                        }""")
                }))
    })
    public BasicMsgWithData<Order> getOrderById(@PathVariable Long id) {
        BasicMsgWithData<Order> msg = new BasicMsgWithData<>();
        try {
            Order order = orderService.getOrderById(id);
            if (order != null) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("查询成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
                msg.setData(order);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_NOT_FOUND);
                msg.setErrorMsg("订单不存在");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_QUERY_FAIL);
            msg.setErrorMsg("查询失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 创建订单
    @PostMapping
    @Operation(summary = "创建订单")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作完成",
            content = @Content(mediaType = "application/json",
                examples = {
                    @ExampleObject(name = "创建成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "订单创建成功，总金额：68.00",
                          "errorCode": "Ok"
                        }"""),
                    @ExampleObject(name = "用户ID不能为空", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "用户ID不能为空",
                          "errorCode": "ORDER_CREATE_FAIL"
                        }"""),
                    @ExampleObject(name = "用户不存在", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "用户不存在",
                          "errorCode": "ORDER_CREATE_FAIL"
                        }"""),
                    @ExampleObject(name = "用户购物车为空", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "用户购物车为空，无法创建订单",
                          "errorCode": "ORDER_CREATE_FAIL"
                        }"""),
                    @ExampleObject(name = "菜品不存在", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "购物车中存在已下架的菜品，无法创建订单",
                          "errorCode": "ORDER_CREATE_FAIL"
                        }"""),
                    @ExampleObject(name = "配送地址不能为空", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "配送地址不能为空",
                          "errorCode": "ORDER_CREATE_FAIL"
                        }"""),
                    @ExampleObject(name = "联系电话不能为空", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "联系电话不能为空",
                          "errorCode": "ORDER_CREATE_FAIL"
                        }"""),
                    @ExampleObject(name = "联系人姓名不能为空", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "联系人姓名不能为空",
                          "errorCode": "ORDER_CREATE_FAIL"
                        }"""),
                    @ExampleObject(name = "多个验证失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "用户ID不能为空; 配送地址不能为空; 联系电话不能为空",
                          "errorCode": "ORDER_CREATE_FAIL"
                        }"""),
                    @ExampleObject(name = "创建失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单创建失败: 具体错误信息",
                          "errorCode": "ORDER_CREATE_FAIL"
                        }""")
                }))
    })
    public BasicMsg createOrder(@RequestBody CreateOrderRequest request) {
        BasicMsg msg = new BasicMsg();
        try {
            // 验证所有字段和业务逻辑，收集所有错误
            StringBuilder validationErrors = new StringBuilder();
            
            // 1. 基本字段验证
            if (request.getUserId() == null) {
                validationErrors.append("用户ID不能为空; ");
            }
            if (request.getDeliveryAddress() == null || request.getDeliveryAddress().trim().isEmpty()) {
                validationErrors.append("配送地址不能为空; ");
            }
            if (request.getContactPhone() == null || request.getContactPhone().trim().isEmpty()) {
                validationErrors.append("联系电话不能为空; ");
            }
            if (request.getContactName() == null || request.getContactName().trim().isEmpty()) {
                validationErrors.append("联系人姓名不能为空; ");
            }
            
            // 2. 用户和购物车综合验证（只有在用户ID不为空时才进行）
            BigDecimal totalAmount = BigDecimal.ZERO;
            if (request.getUserId() != null) {
                // 验证用户是否存在
                if (sysUserService.getUserById(request.getUserId()) == null) {
                    validationErrors.append("用户不存在; ");
                } else {
                    // 用户存在时，验证购物车和菜品
                    List<Cart> cartItems = cartService.getUserCart(request.getUserId());
                    if (cartItems == null || cartItems.isEmpty()) {
                        validationErrors.append("用户购物车为空，无法创建订单; ");
                    } else {
                        // 计算总金额并验证菜品
                        for (Cart cartItem : cartItems) {
                            DishWithBLOBs dish = dishService.getDishById(cartItem.getDishId());
                            if (dish == null || !"0".equals(dish.getDishStatus())) {
                                validationErrors.append("购物车中存在已下架的菜品，无法创建订单; ");
                                break;
                            }
                            // 计算小计：数量 × 单价
                            BigDecimal itemTotal = dish.getDishPrice().multiply(BigDecimal.valueOf(cartItem.getQuantity()));
                            totalAmount = totalAmount.add(itemTotal);
                        }
                    }
                }
            }
            
            // 如果有任何验证错误，返回所有错误（单个或多个）
            if (validationErrors.length() > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_CREATE_FAIL);
                msg.setErrorMsg(validationErrors.toString().trim());
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                return msg;
            }
            
            // 创建 Order 对象
            Order order = new Order();
            order.setUserId(request.getUserId());
            order.setTotalAmount(totalAmount); // 使用计算出的总金额
            order.setDeliveryAddress(request.getDeliveryAddress());
            order.setContactPhone(request.getContactPhone());
            order.setContactName(request.getContactName());
            order.setRemark(request.getRemark());
            // 设置默认订单状态为待支付
            order.setOrderStatus("0");
            
            int result = orderService.createOrder(order);
            if (result > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("订单创建成功，总金额：" + totalAmount);
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_CREATE_FAIL);
                msg.setErrorMsg("订单创建失败");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_CREATE_FAIL);
            msg.setErrorMsg("订单创建失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 更新订单
    @PutMapping("/{id}")
    @Operation(summary = "更新订单")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作完成",
            content = @Content(mediaType = "application/json",
                examples = {
                    @ExampleObject(name = "更新成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "订单更新成功",
                          "errorCode": "Ok"
                        }"""),
                    @ExampleObject(name = "配送地址不能为空", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "配送地址不能为空",
                          "errorCode": "ORDER_MODIFY_FAIL"
                        }"""),
                    @ExampleObject(name = "联系电话不能为空", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "联系电话不能为空",
                          "errorCode": "ORDER_MODIFY_FAIL"
                        }"""),
                    @ExampleObject(name = "联系人姓名不能为空", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "联系人姓名不能为空",
                          "errorCode": "ORDER_MODIFY_FAIL"
                        }"""),
                    @ExampleObject(name = "多个验证失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "配送地址不能为空; 联系电话不能为空; 联系人姓名不能为空",
                          "errorCode": "ORDER_MODIFY_FAIL"
                        }"""),
                    @ExampleObject(name = "订单不存在", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单不存在",
                          "errorCode": "ORDER_MODIFY_FAIL"
                        }"""),
                    @ExampleObject(name = "更新失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单更新失败: 具体错误信息",
                          "errorCode": "ORDER_MODIFY_FAIL"
                        }""")
                }))
    })
    public BasicMsg updateOrder(@PathVariable Long id, @RequestBody UpdateOrderRequest request) {
        BasicMsg msg = new BasicMsg();
        try {
            // 验证所有字段，收集所有错误
            StringBuilder validationErrors = new StringBuilder();
            
            // 验证必填字段
            if (request.getDeliveryAddress() == null || request.getDeliveryAddress().trim().isEmpty()) {
                validationErrors.append("配送地址不能为空; ");
            }
            if (request.getContactPhone() == null || request.getContactPhone().trim().isEmpty()) {
                validationErrors.append("联系电话不能为空; ");
            }
            if (request.getContactName() == null || request.getContactName().trim().isEmpty()) {
                validationErrors.append("联系人姓名不能为空; ");
            }
            
            // 如果有任何验证错误，返回所有错误（单个或多个）
            if (validationErrors.length() > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_MODIFY_FAIL);
                msg.setErrorMsg(validationErrors.toString().trim());
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                return msg;
            }
            
            // 先查询现有订单，确保订单存在
            Order existingOrder = orderService.getOrderById(id);
            if (existingOrder == null) {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_MODIFY_FAIL);
                msg.setErrorMsg("订单不存在");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                return msg;
            }
            
            // 创建更新后的订单对象，只更新允许的字段
            Order order = new Order();
            order.setOrderId(id);
            order.setDeliveryAddress(request.getDeliveryAddress());
            order.setContactPhone(request.getContactPhone());
            order.setContactName(request.getContactName());
            order.setRemark(request.getRemark());
            // 保持原有字段不变
            order.setOrderNo(existingOrder.getOrderNo());
            order.setUserId(existingOrder.getUserId());
            order.setTotalAmount(existingOrder.getTotalAmount());
            order.setOrderStatus(existingOrder.getOrderStatus());
            order.setPaymentMethod(existingOrder.getPaymentMethod());
            order.setPaymentTime(existingOrder.getPaymentTime());
            order.setCreateTime(existingOrder.getCreateTime());
            order.setUpdateTime(null); // 更新时间由服务层自动设置
            
            int result = orderService.updateOrder(order);
            if (result > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("订单更新成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_MODIFY_FAIL);
                msg.setErrorMsg("订单更新失败");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_MODIFY_FAIL);
            msg.setErrorMsg("订单更新失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 删除订单
    @DeleteMapping("/{id}")
    @Operation(summary = "删除订单")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作完成",
            content = @Content(mediaType = "application/json",
                examples = {
                    @ExampleObject(name = "删除成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "订单删除成功",
                          "errorCode": "Ok"
                        }"""),
                    @ExampleObject(name = "删除失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单删除失败",
                          "errorCode": "ORDER_DELETE_FAIL"
                        }"""),
                    @ExampleObject(name = "系统错误", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单删除失败: 具体错误信息",
                          "errorCode": "ORDER_DELETE_FAIL"
                        }""")
                }))
    })
    public BasicMsg deleteOrder(@PathVariable Long id) {
        BasicMsg msg = new BasicMsg();
        try {
            int result = orderService.deleteOrder(id);
            if (result > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("订单删除成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_DELETE_FAIL);
                msg.setErrorMsg("订单删除失败");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_DELETE_FAIL);
            msg.setErrorMsg("订单删除失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 根据用户ID获取订单
    @GetMapping("/user/{userId}")
    @Operation(summary = "根据用户ID获取订单")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功",
            content = @Content(mediaType = "application/json", 
                examples = {
                    @ExampleObject(name = "查询成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": [
                            {
                              "orderNo": "ORD1736316000000",
                              "userId": 1,
                              "totalAmount": 56.00,
                              "orderStatus": "1",
                              "paymentMethod": "微信支付",
                              "paymentTime": "2025-10-08T14:05:00",
                              "deliveryAddress": "北京市朝阳区xxx街道",
                              "contactPhone": "13800138000",
                              "contactName": "张三",
                              "remark": "请尽快送达"
                            }
                          ]
                        }"""),
                    @ExampleObject(name = "该用户暂无订单", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "该用户暂无订单",
                          "errorCode": "ORDER_NOT_FOUND",
                          "data": null
                        }"""),
                    @ExampleObject(name = "查询失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "查询失败: 数据库连接异常",
                          "errorCode": "ORDER_QUERY_FAIL",
                          "data": null
                        }""")
                }))
    })
    public BasicMsgWithData<List<Order>> getOrdersByUserId(@PathVariable Long userId) {
        BasicMsgWithData<List<Order>> msg = new BasicMsgWithData<>();
        try {
            List<Order> orders = orderService.getOrdersByUserId(userId);
            if (orders != null && !orders.isEmpty()) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("查询成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
                msg.setData(orders);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_NOT_FOUND);
                msg.setErrorMsg("该用户暂无订单");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                msg.setData(null);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_QUERY_FAIL);
            msg.setErrorMsg("查询失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            msg.setData(null);
        }
        return msg;
    }
    
    // 根据订单号查询订单
    @GetMapping("/orderNo/{orderNo}")
    @Operation(summary = "根据订单号查询订单")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功",
            content = @Content(mediaType = "application/json", 
                examples = {
                    @ExampleObject(name = "查询成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": {
                            "orderNo": "ORD1736316000000",
                            "userId": 1,
                            "totalAmount": 56.00,
                            "orderStatus": "1",
                            "paymentMethod": "微信支付",
                            "paymentTime": "2025-10-08T14:05:00",
                            "deliveryAddress": "北京市朝阳区xxx街道",
                            "contactPhone": "13800138000",
                            "contactName": "张三",
                            "remark": "请尽快送达"
                          }
                        }"""),
                    @ExampleObject(name = "订单不存在", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单不存在",
                          "errorCode": "ORDER_NOT_FOUND",
                          "data": null
                        }"""),
                    @ExampleObject(name = "查询失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "查询失败: 数据库连接异常",
                          "errorCode": "ORDER_QUERY_FAIL",
                          "data": null
                        }""")
                }))
    })
    public BasicMsgWithData<Order> getOrderByOrderNo(@PathVariable String orderNo) {
        BasicMsgWithData<Order> msg = new BasicMsgWithData<>();
        try {
            Order order = orderService.getOrderByOrderNo(orderNo);
            if (order != null) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("查询成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
                msg.setData(order);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_NOT_FOUND);
                msg.setErrorMsg("订单不存在");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_QUERY_FAIL);
            msg.setErrorMsg("查询失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 根据订单状态查询订单
    @GetMapping("/status/{status}")
    @Operation(summary = "根据订单状态查询订单")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功",
            content = @Content(mediaType = "application/json", 
                examples = {
                    @ExampleObject(name = "查询成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": [
                            {
                              "orderNo": "ORD1736316000000",
                              "userId": 1,
                              "totalAmount": 56.00,
                              "orderStatus": "1",
                              "paymentMethod": "微信支付",
                              "paymentTime": "2025-10-08T14:05:00",
                              "deliveryAddress": "北京市朝阳区xxx街道",
                              "contactPhone": "13800138000",
                              "contactName": "张三",
                              "remark": "请尽快送达"
                            }
                          ]
                        }"""),
                    @ExampleObject(name = "该状态暂无订单", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "该状态暂无订单",
                          "errorCode": "ORDER_NOT_FOUND",
                          "data": null
                        }"""),
                    @ExampleObject(name = "查询失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "查询失败: 数据库连接异常",
                          "errorCode": "ORDER_QUERY_FAIL",
                          "data": null
                        }""")
                }))
    })
    public BasicMsgWithData<List<Order>> getOrdersByStatus(@PathVariable String status) {
        BasicMsgWithData<List<Order>> msg = new BasicMsgWithData<>();
        try {
            List<Order> orders = orderService.getOrdersByStatus(status);
            if (orders != null && !orders.isEmpty()) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("查询成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
                msg.setData(orders);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_NOT_FOUND);
                msg.setErrorMsg("暂无该状态的订单");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                msg.setData(null);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_QUERY_FAIL);
            msg.setErrorMsg("查询失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            msg.setData(null);
        }
        return msg;
    }
    
    // 取消订单
    @PutMapping("/{id}/cancel")
    @Operation(summary = "取消订单")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作完成",
            content = @Content(mediaType = "application/json",
                examples = {
                    @ExampleObject(name = "取消成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "订单取消成功",
                          "errorCode": "Ok"
                        }"""),
                    @ExampleObject(name = "订单状态不正确", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "只有待支付的订单才能取消",
                          "errorCode": "ORDER_STATUS_INVALID"
                        }"""),
                    @ExampleObject(name = "取消失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单取消失败",
                          "errorCode": "ORDER_CANCEL_FAIL"
                        }"""),
                    @ExampleObject(name = "系统错误", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单取消失败: 具体错误信息",
                          "errorCode": "ORDER_CANCEL_FAIL"
                        }""")
                }))
    })
    public BasicMsg cancelOrder(@PathVariable Long id) {
        BasicMsg msg = new BasicMsg();
        try {
            int result = orderService.cancelOrder(id);
            if (result > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("订单取消成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            } else if (result == -1) {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_STATUS_INVALID);
                msg.setErrorMsg("只有待支付的订单才能取消");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_CANCEL_FAIL);
                msg.setErrorMsg("订单取消失败");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_CANCEL_FAIL);
            msg.setErrorMsg("订单取消失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 支付订单
    @PutMapping("/{id}/pay")
    @Operation(summary = "支付订单")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作完成",
            content = @Content(mediaType = "application/json",
                examples = {
                    @ExampleObject(name = "支付成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "支付成功",
                          "errorCode": "Ok"
                        }"""),
                    @ExampleObject(name = "订单状态不正确", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单状态不正确",
                          "errorCode": "ORDER_STATUS_INVALID"
                        }"""),
                    @ExampleObject(name = "支付失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "支付失败",
                          "errorCode": "ORDER_PAY_FAIL"
                        }"""),
                    @ExampleObject(name = "系统错误", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "支付失败: 具体错误信息",
                          "errorCode": "ORDER_PAY_FAIL"
                        }""")
                }))
    })
    public BasicMsg payOrder(@PathVariable Long id, @RequestBody Map<String, String> paymentData) {
        BasicMsg msg = new BasicMsg();
        try {
            String paymentMethod = paymentData.get("paymentMethod");
            int result = orderService.payOrder(id, paymentMethod);
            if (result > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("支付成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            } else if (result == -1) {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_STATUS_INVALID);
                msg.setErrorMsg("订单状态不正确");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_PAY_FAIL);
                msg.setErrorMsg("支付失败");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_PAY_FAIL);
            msg.setErrorMsg("支付失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
}
